/* eslint-disable */
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '@/router/index'
import { useAccountStore } from '@/stores/userInfo'
import { baseURL } from '@/config/index'
// 请求超时时间，10s
const requestTimeOut = 10 * 1000
const success = 200
// 更换令牌的时间区间
const checkRegion = 5 * 60 * 1000
// 提示信息显示时长
const messageDuration = 5 * 1000
let messageCounter = 0
// 系统全局请求对象
export const service = axios.create({
  baseURL: baseURL,
  timeout: requestTimeOut,
  responseType: 'json',
  validateStatus(status) {
    return status === success
  }
})

// 系统令牌刷新请求对象
const refresh_service = axios.create({
  baseURL: baseURL,
  timeout: requestTimeOut,
  responseType: 'json',
  validateStatus(status) {
    return status === success
  }
})

service.interceptors.request.use(
  (config) => {
    let _config = config
    try {
      // const expireTime = getExpireTime()
      const { token, httpUrl } = useAccountStore()
      if (token) {
        _config.headers['Authorization'] = token
        // console.log('_config', _config)
        _config.url = _config.url + 'token=' + token
      } else {
        if (!messageCounter) {
        }
      }
      if (httpUrl) {
        _config.baseURL = httpUrl
      }
    } catch (e) {
      console.error(e)
    }
    return _config
  },
  (error) => {
    console.log(error)
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (config) => {
    if (config.data.code == 0) {
      return config.data.data
    } else if (config.data.code === 503) {
      if (!messageCounter) {
        messageCounter++
      }
    }
    return config.data
  },
  (error) => {
    if (error.response) {
      // console.log('error', error)
      const errorMessage =
        error.response.data === null
          ? '系统内部异常，请联系网站管理员'
          : error.response.data.message
      switch (error.response.status) {
        case 404:
          ElMessage({
            message: '很抱歉，资源未找到',
            type: 'error',
            duration: messageDuration
          })
          break
        case 403:
          ElMessage({
            message: '很抱歉，您暂无该操作权限',
            type: 'error',
            duration: messageDuration
          })
          break
        case 401:
          // ElMessage({
          //   message: "很抱歉，认证已失效，请重新登录",
          //   type: "error",
          //   duration: messageDuration
          // });
          // clearToken()
          // store.state.account.accessToken = ''
          // router.push("/login");
          break
        default:
          if (errorMessage === 'refresh token无效') {
            ElMessageBox.alert('登录已过期，请重新登录', '温馨提示', {
              confirmButtonText: '确定',
              showClose: false,
              callback: () => {
                router.push('/login')
              }
            })
          } else {
            ElMessage({
              message: errorMessage,
              type: 'error',
              duration: messageDuration
            })
          }
          break
      }
    }
    return Promise.reject(error)
  }
)

const request = {
  refresh(url: string, params: any) {
    params['grant_type'] = 'refresh_token'
    return refresh_service.post(url, params, {
      transformRequest: [
        (params) => {
          return tansParams(params)
        }
      ]
    })
  },
  login(url: string, params: any) {
    params['grant_type'] = 'password'
    return service.post(url, params, {
      transformRequest: [
        (params) => {
          return tansParams(params)
        }
      ],
      headers: {
        Authorization: 'Basic b2xpdmUtd2ViOjEyMzQ1Ng=='
      }
    })
  },
  post(url: string, params: any) {
    return service.post(url, params, {
      transformRequest: [
        (params) => {
          return tansParams(params)
        }
      ],
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  },
  put(url: string, params: any) {
    return service.put(url, params, {
      transformRequest: [
        (params) => {
          return tansParams(params)
        }
      ],
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  },
  get(url: string, params: any) {
    let _params
    if (Object.is(params, undefined)) {
      _params = ''
    } else {
      _params = '?'
      for (const key in params) {
        // eslint-disable-next-line no-prototype-builtins
        if (params.hasOwnProperty(key) && params[key] !== null) {
          _params += `${key}=${params[key]}&`
        }
      }
    }
    return service.get(`${url}${_params}`)
  },
  delete(url: string, params: any) {
    let _params
    if (Object.is(params, undefined)) {
      _params = ''
    } else {
      _params = '?'
      for (const key in params) {
        // eslint-disable-next-line no-prototype-builtins
        if (params.hasOwnProperty(key) && params[key] !== null) {
          _params += `${key}=${params[key]}&`
        }
      }
    }
    return service.delete(`${url}${_params}`)
  }
}

function tansParams(params: any) {
  let result = ''
  Object.keys(params).forEach((key) => {
    if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
      result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
    }
  })
  return result
}

export default request
